const express = require('express');
const fs = require('fs');
const https = require('https');
const cors = require('cors');
const { Server } = require('socket.io');

const app = express();

// 使用 CORS 中间件
app.use(cors({
  origin: "*", // 确保与前端的HTTPS端口一致
  methods: ["GET", "POST"],
  allowedHeaders: ["Content-Type"]
}));

// 读取 mkcert 生成的 SSL 证书
const privateKey = fs.readFileSync('./ssl/localhost-key.pem', 'utf8');
const certificate = fs.readFileSync('./ssl/localhost.pem', 'utf8');
const credentials = { key: privateKey, cert: certificate };

// 创建 HTTPS 服务器
const httpsServer = https.createServer(credentials, app);

// 初始化 Socket.io，并使用 HTTPS 服务器
const io = new Server(httpsServer, {
  cors: {
    origin: '*',
    methods: ["GET", "POST"]
  }
});

// 存储客户端ID的映射
const clients = {};
const userCallStatus = {};


io.on('connection', socket => {
  const clientIp = socket.handshake.address;
  console.log(`客户端已连接: ${clientIp}`);

  // 注册用户ID和对应的socket ID
  socket.on('register', userId => {
    clients[userId] = socket.id;
    const userIds =  Object.keys(clients)
    userIds.forEach(id=>{
      // 通知每个在线的用户，有新用户上线了
      console.log(userIds)
      socket.to(clients[id]).emit('update-user', { newUserId: userId, userIds });
    })
    console.log(`注册用户ID和对应的socket ID:${userId} ， socket ID ${socket.id}`);
    socket.emit('update-users', { userIds }); // 通知当前注册用户更新用户列表
  });

  // 处理 call 消息
  socket.on('call', ({ calleeId, callerId }) => {
    if (userCallStatus[calleeId]) {
      console.log('---------对方正在通话中')
      // 检查呼叫方是否正在通话中
      socket.emit('busy', { calleeId });
      return
    }
    console.log(`call消息: 通知${calleeId} , ${callerId}申请打电话`);
    if (clients[calleeId]) {
      userCallStatus[calleeId] = [calleeId, callerId]; // 方便在连接断开时通知另外一方
      userCallStatus[callerId] = [calleeId, callerId]; // 方便在连接断开时通知另外一方
      socket.to(clients[calleeId]).emit('call', { calleeId, callerId });
    } else {
      console.log(`Callee ${calleeId} not found`);
    }
  });

  // 处理 offer 消息
  socket.on('offer', ({ offer, calleeId, callerId }) => {
    console.log(`Offer received from ${clientIp}`);
    if (clients[calleeId]) {
      socket.to(clients[calleeId]).emit('offer', {offer, calleeId, callerId});
    } else {
      console.log(`Callee ${calleeId} not found`);
    }
  });

  // 处理 answer 消息
  socket.on('answer', ({ answer, callerId }) => {
    console.log(`收到answer应答请求来自IP: ${clientIp}  呼叫方id: ${callerId}`);
    if (clients[callerId]) {
      socket.to(clients[callerId]).emit('answer', { answer, callerId });
    } else {
      console.log(`Callee ${callerId} not found`);
    }
  });

  // 处理 candidate 消息
  socket.on('candidate', ({ candidate, calleeId }) => {
    console.log(`处理candidate消息，来自IP：${clientIp} , id：${calleeId}`);
    if (clients[calleeId]) {
      console.log(`${clientIp} 正在呼叫对方: ,对方id ${calleeId}`);
      socket.to(clients[calleeId]).emit('candidate', { candidate, calleeId });
    } else {
      console.log(`Callee ${calleeId} not found`);
    }
  });

  // 处理 hangUp 消息
  socket.on('hangUp', ({ calleeId }) => {
    console.log(`收到来自 ${clientIp}  挂断${calleeId}电话的申请`);
    if (clients[calleeId]) {
      const callingUsers = userCallStatus[calleeId]; // 获取正在通话中的两个人的ID
      callingUsers?.forEach(userId => {
        delete userCallStatus[userId]
      })
      console.log('-------------完成通话状态的删除')
      console.log('------------', userCallStatus)
      socket.to(clients[calleeId]).emit('hangUp');
    } else {
      console.log(`Callee ${calleeId} not found`);
    }
  });

  // 处理 resolveCall 消息
  socket.on('resolveCall', ({ calleeId, callerId }) => {
    console.log(`$${calleeId}同意接听${callerId}发起的通话`);
    if (clients[callerId]) {
      socket.to(clients[callerId]).emit('resolveCall');
    } else {
      console.log(`Callee ${callerId} not found`);
    }
  });
  // 处理 rejectCall 消息
  socket.on('rejectCall', ({ calleeId, callerId }) => {
    if(userCallStatus[calleeId]){
      // 清除通话中的状态
      delete userCallStatus[calleeId]
    }
    if(userCallStatus[callerId]){
      // 清除通话中的状态
      delete userCallStatus[callerId];
    }
    console.log(`$${calleeId}拒绝接听${callerId}发起的通话`);
    if (clients[calleeId]) {
      socket.to(clients[callerId]).emit('rejectCall');
    } else {
      console.log(`Callee ${callerId} not found`);
    }
  });

  // 客户端断开连接时
  socket.on('disconnect', () => {
    console.log(`客户端已断开连接: ${clientIp}`);
    let disconnectUserId = ''
    for (const [userId, socketId] of Object.entries(clients)) {
      if (socketId === socket.id) {
        disconnectUserId = userId
        delete clients[userId];
        const callingUsers = userCallStatus[userId]; // 获取正在通话中的两个人的ID
        callingUsers?.forEach(id => {
          delete userCallStatus[id]
          if(id !== userId) {
            // 通知还在线的一方对方已掉线
            console.log(`通知${id} ${userId}已掉线`)
            socket.to(clients[id]).emit('over-disconnect', userId);
          }
        })
        console.log(`删除掉线用户： ${userId}`);
        break;
      }
    }
    const userIds =  Object.keys(clients)
    userIds.forEach(id=>{
      // 通知每个在线的用户，有新用户下线了
      socket.to(clients[id]).emit('delete-user', { disconnectUserId, userIds });
    })
  });
});

const PORT = 3000;
httpsServer.listen(PORT, () => {
  console.log(`Signaling server is running on https://localhost:${PORT}`);
});
